package com.solocredit.finance.ui.main.act

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.BaseFragment
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.base.utils.helper.ActivityStackManager
import com.solocredit.finance.base.utils.helper.ForegroundBackgroundHelper
import com.solocredit.finance.base.utils.helper.ForegroundBackgroundObserver
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.databinding.ActMullaMainBinding
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.main.adapter.MullaTabAdapter
import com.solocredit.finance.ui.main.impl.MullaMainPresenterImpl
import com.solocredit.finance.ui.main.view.IMullaMainView
import com.solocredit.finance.ui.user.act.MullaUserVerificationAct
import com.solocredit.finance.utils.DateUtils
import com.solocredit.finance.utils.dialog.SignDialog
import com.solocredit.finance.utils.dialog.VersionUpdateDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.utils.helper.MullaUserCouponHelper
import com.solocredit.finance.utils.helper.MullaVersionUpdateHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject
import java.util.TimeZone

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:42
 * @Annotation：主页
 */

class MullaMainAct : MvpAct<IMullaMainView, MullaMainPresenterImpl>(),IMullaMainView {
    lateinit var binding: ActMullaMainBinding

    private var tabAdapter: MullaTabAdapter? = null

    private var fragmentManager: FragmentManager? = null
    private var curtFragment: BaseFragment? = null

    private var updateHelper: MullaVersionUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // 更新成功
        } else {
        }
    }

    override fun getMullaRootView(): View {
        binding = ActMullaMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): MullaMainPresenterImpl {
        return MullaMainPresenterImpl(this)
    }

    override fun initMullaView() {
        setBackExit(true)
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initMullaRecyclerView()

        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initMullaListener() {

    }

    override fun initMullaData() {
        //保存时区id，用于判断是否切换时区
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_ID, TimeZone.getDefault().id)

        presenter.loadMullaTabList()
        presenter.loadMullaFragmentList()
        presenter.loadMullaProcessAction()
        //加载保存自定义数据
        MullaCustomDataHelper.loadMullaCustomDataAction()

        //是否有新版本
        val isUpdate = MullaCustomConfigsHelper.isMullaVersionUpdate()
        if (isUpdate){
            showMullaVersionUpdateDialog()
        }
    }

    /**
     * 初始化Tab列表
     */
    private fun initMullaRecyclerView() {
        binding.recyclerView.layoutManager = GridLayoutManager(getContext(), 4)
        tabAdapter = MullaTabAdapter(binding.recyclerView)
        binding.recyclerView.adapter = tabAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {//切换item
                presenter.setMullaCurrentItemIndex(position)
            }
        })
    }

    /**
     * 设置tabList
     */
    override fun showMullaTabList(tabList: ArrayList<JSONObject>) {
        tabAdapter?.data = tabList
    }

    /**
     * 刷新Tab
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun notifyTabDataChanged() {
        if (tabAdapter != null){
            tabAdapter?.notifyDataSetChanged()
        }
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    override fun showMullaFragment(fragment: BaseFragment, index: Int) {
        //设置状态栏文字颜色
        showMullaStatusBarLightMode(index)
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        val transaction = fragmentManager?.beginTransaction()
        transaction?.let { transaction ->
            curtFragment?.let {
                transaction.hide(it)
            }
            //如果之前没有添加过
            if (!fragment.isAdded) {
                //第三个参数为添加当前的fragment时绑定一个tag
                transaction.add(R.id.contentLayout, fragment, fragment.javaClass.canonicalName)
            } else {
                transaction.show(fragment)

                if (index == 0 || index == 1){
                    //刷新产品列表
                    presenter.loadMullaProductListAction()
                }
            }
            curtFragment = fragment
            transaction.commitAllowingStateLoss()
        }
    }

    /**
     * 签到成功
     */
    override fun showMullaSignSuccessDialog(points: String) {
        val signDialog = SignDialog(this,object : SignDialog.IDialogCallback{
            override fun onClick(view: View?) {
                // TODO: 2025/10/16 更新为不跳转
                //切换到兑换优惠券页面
//                presenter.setMullaCurrentItemIndex(2)
            }
            override fun onDismiss() {
            }
        })
        signDialog.setCancelable(true)
        signDialog.setCanceledOnTouchOutside(false)
        signDialog.show()
        signDialog.showMullaPoints(points)
    }

    /**
     * 版本更新Dialog
     */
    private fun showMullaVersionUpdateDialog(){
        val lastShowTime = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_VERSION_UPDATE_LAST_TIME)
        if (lastShowTime.isNotEmpty() && DateUtils.isSameDay(lastShowTime.toLong(),System.currentTimeMillis())){
            return
        }
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_VERSION_UPDATE_LAST_TIME,"${System.currentTimeMillis()}")
        val updateDialog = VersionUpdateDialog(this,"Home page",object : VersionUpdateDialog.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = MullaVersionUpdateHelper(this@MullaMainAct, false, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { }
                } catch (e: Exception) {
                }
            }
        })
        updateDialog.show()
    }

    /**
     * 进入手机号校验页面
     */
    override fun ShowMullaVerificationPage() {
        //当前栈顶是 手机号校验页面 不重复跳转
        if (ActivityStackManager.isCurrentActivity(MullaUserVerificationAct::class.java)){
            return
        }
        //是否是审核账号
        val isConfigAccount = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，直接不走校验
            return
        }
        MullaUserVerificationAct.start(this)
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            if (isForeground) {
                //从桌面进入前台，需要刷新总流程
//                Apps.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESH))
                //刷新产品列表
                presenter.loadMullaProductListAction()
                //刷新积分
                MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_POINTS_REFRESH))
            }
        }
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        when(event.eventType){
            MullaEventData.TYPE.MULLA_PROCESS_REFRESH -> {//刷新流程
                presenter.loadMullaProcessAction()
            }
            MullaEventData.TYPE.MULLA_SHOW_HOME -> {//显示首页
                presenter.setMullaCurrentItemIndex(0)
            }
            MullaEventData.TYPE.MULLA_SHOW_REPAY -> {//待还款
                presenter.setMullaCurrentItemIndex(1)
            }
            MullaEventData.TYPE.MULLA_SHOW_COUPON_CENTER -> {//优惠券中心
                presenter.setMullaCurrentItemIndex(2)
            }
            MullaEventData.TYPE.MULLA_POINTS_REFRESH -> {//刷新积分
                presenter.loadMullaUserSignInfoAction()
                //刷新优惠券
                MullaUserCouponHelper.loadMullaUserCouponListAction()
            }
            MullaEventData.TYPE.MULLA_PRODUCT_REFRESH -> {//刷新产品
                presenter.loadMullaProductListAction()
            }
            else -> {

            }
        }
        MullaLog.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
    }

    private fun showMullaStatusBarLightMode(index: Int){
        when(index){
            0,1 -> {
                TitleBarUtil.setStatusBarLightMode(this, true)
            }
            else -> {
                TitleBarUtil.setStatusBarLightMode(this, false)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.resumeIfInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}